<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
-->
<!-- 
* @desc:任务编排新增弹窗
* @fileName:Operation.vue
* @author:chenxiaofeng@yzbdl.ac.cn
* @date:2022-4-15
!-->
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import TreeDialog from "./tree-dialog.vue";
import { showErrorMessage } from "../../../../common/message";
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;

const props = defineProps({
  // 保存方法回调
  saveResource: Function as any,
  // 修改方法回调
  editResource: Function as any,
  // 新增或编辑文字
  addOrEdit: String,
  // 编辑时传回的当前行数据
  oneUserInfo: Object,
});

// 资源类型值
let resourceLib: any = [];

/**
 * 任务资源数据
 */
const groupTreeList = reactive({
  treeList: [] as any,
  treeDialog: false,
  resourceValue: "",
  resourceLibOptions: [] as any,
});

const formSize: any = ref("default");
const editId = ref("");
const ruleFormRef = ref<FormInstance>();

/**
 * 表单数据
 */
const ruleForm = reactive({
  resourceType: "",
  resourceConfigId: "",
  groupId: "",
  resourceName: "",
  resourcePath: "",
  resourceAccountName: "",
  resourcePassword: "",
});
const labelPosition = ref("top");

/**
 * 定义校验规则
 */
const rules: any = reactive({
  resourceName: [
    { required: true, message: "请输入资源名称", trigger: "blur" },
    { max: 64, message: "资源名称最多能输入64个字符", trigger: "blur" },
  ],
  resourceConfigId: [
    { required: true, message: "请选择资源库", trigger: "blur" },
  ],
  resourceType: [
    { required: true, message: "请选择资源类型", trigger: "blur" },
  ],
  resourcePath: [{ required: true, message: "请选择资源", trigger: "blur" }],
  resourceAccountName: [
    { required: true, message: "请输入任务资源账户名", trigger: "blur" },
    { max: 64, message: "任务资源账户名最多能输入64个字符", trigger: "blur" },
  ],
  resourcePassword: [
    { required: true, message: "请输入任务资源密码", trigger: "blur" },
    {
      min: 1,
      max: 20,
      message: "任务资源密码位数必须是1-20个字符",
      trigger: "blur",
    },
  ],
});

/**
 * 提交表单
 * @reture viod
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let saveObj: { [key: string]: any } = {
        resourceType: ruleForm.resourceType,
        resourceConfigId: ruleForm.resourceConfigId,
        groupId: ruleForm.groupId,
        resourceName: ruleForm.resourceName,
        resourcePath: ruleForm.resourcePath,
        resourceAccountName: ruleForm.resourceAccountName,
        resourcePassword: ruleForm.resourcePassword,
      };
      if (props.addOrEdit === "新增") {
        props.saveResource(saveObj);
      } else {
        saveObj.id = editId.value;
        props.editResource(saveObj);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * 获取资源库列表
 * @reture viod
 */
const getResourceLibList = () => {
  const res = proxy.$HTTP.post({
    url: "/resource/taskResourceConfig/query",
    params: {
      page: 1,
      size: 500,
    },
    data: {
      connectName: "",
      status: "1",
    },
  });
  res
    .then((res: any) => {
      if (res.isOk) {
        resourceLib = res.data.records;
        groupTreeList.resourceLibOptions = resourceLib.map((item: any) => ({
          value: item.id,
          label: item.connectName,
        }));
      }
    })
    .catch((response: any) => {
      showErrorMessage({ message: response.data });
    });
};

/**
 * 获取资源配置列表
 * @param id 资源ID
 * @reture viod
 */
const getGroupList = (id: string) => {
  ruleForm.resourcePath = "";
  const res = proxy.$HTTP.get({
    url: "/resource/taskResource/getExternalResourceTree",
    params: {
      resourceConfigId: id,
    },
  });
  res
    .then((res: any) => {
      if (res.code === 200) {
        groupTreeList.treeList = res.data;
        const nodeData: any = {
          id: "0",
          nodeName: "根节点任务资源",
          path: "",
          children: [],
        };
        groupTreeList.treeList.unshift(nodeData);
      }
    })
    .catch((response: any) => {
      showErrorMessage({ message: response.data });
    });
};

/**
 * 获取资源路径数据
 * @param path 资源路径
 * @reture viod
 */
const getGroupInfo = (path: string) => {
  ruleForm.resourcePath = path;
  groupTreeList.treeDialog = false;
};

/**
 * 打开选择资源弹窗
 * @reture viod
 */
const chooseResource = () => {
  if (ruleForm.resourceConfigId === "") {
    ElMessage.info("请先选择资源库!");
  } else {
    groupTreeList.treeDialog = true;
  }
};

onMounted(() => {
  getResourceLibList();
  let userInfo = { ...props.oneUserInfo };
  if (JSON.stringify(props.oneUserInfo) !== "{}") {
    getGroupList(userInfo.resourceConfigId);
    editId.value = userInfo.id;
    ruleForm.resourceType = userInfo.resourceType.toString();
    ruleForm.resourceConfigId = userInfo.resourceConfigId;
    ruleForm.groupId = userInfo.groupId;
    ruleForm.resourceAccountName = JSON.parse(
      userInfo.resourceContent
    ).repo_account;
    ruleForm.resourcePassword = JSON.parse(
      userInfo.resourceContent
    ).repo_password;
    ruleForm.resourceName = userInfo.resourceName;
    ruleForm.resourcePath = JSON.parse(userInfo.resourceContent).repo_entrance;
    groupTreeList.resourceValue = JSON.parse(userInfo.resourceContent)
      .repo_entrance.split(".")[0]
      .split("/")
      .pop();
  }
});
</script>

<template>
  <div class="operation">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      :label-position="labelPosition"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
    >
      <el-form-item label="资源名称" prop="resourceName">
        <el-input
          v-model="ruleForm.resourceName"
          size="large"
          placeholder="请输入资源名称"
        />
      </el-form-item>
      <el-form-item label="资源库" prop="resourceConfigId">
        <el-select-v2
          v-model="ruleForm.resourceConfigId"
          size="large"
          placeholder="请选择资源库"
          @change="getGroupList"
          :options="groupTreeList.resourceLibOptions"
        ></el-select-v2>
      </el-form-item>
      <el-form-item label="资源类型" prop="resourceType">
        <el-select
          v-model="ruleForm.resourceType"
          size="large"
          clearable
          placeholder="请选择资源类型"
          @change="ruleForm.resourcePath = ''"
        >
          <el-option label="作业" value="1"></el-option>
          <el-option label="转换" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="任务资源账户名"
        v-show="ruleForm.resourceType !== ''"
        prop="resourceAccountName"
      >
        <el-input
          v-model="ruleForm.resourceAccountName"
          size="large"
          placeholder="请输入任务资源账户名"
        />
      </el-form-item>
      <el-form-item
        label="任务资源密码"
        v-show="ruleForm.resourceType !== ''"
        prop="resourcePassword"
      >
        <el-input
          v-model="ruleForm.resourcePassword"
          size="large"
          type="password"
          placeholder="请输入任务资源密码"
        />
      </el-form-item>
      <el-form-item label="资源" prop="resourcePath" :inline-message="true">
        <el-col :span="20">
          <el-input
            v-model="ruleForm.resourcePath"
            :disabled="true"
            placeholder="请选择资源"
            size="large"
          ></el-input>
        </el-col>
        <el-col :span="4" class="tar">
          <el-button size="large" @click="chooseResource">选择资源</el-button>
        </el-col>
      </el-form-item>
      <el-form-item class="ClickButton">
        <el-button @click="submitForm(ruleFormRef)">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 操作弹窗 -->
  <el-dialog
    v-model="groupTreeList.treeDialog"
    v-if="groupTreeList.treeDialog"
    title="选择资源"
    :width="740"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <TreeDialog
      :groupTreeList="groupTreeList.treeList"
      :resourceConfigId="ruleForm.resourceConfigId"
      :resourceType="ruleForm.resourceType"
      :resourceValue="groupTreeList.resourceValue"
      :getGroupInfo="getGroupInfo"
    />
  </el-dialog>
</template>

<style>
.el-dialog__header {
  border-bottom: 1px solid #dedede;
  margin-right: 0;
}
</style>
<style scoped lang="scss">
.tar {
  text-align: right;
}
:deep(.el-form-item__label) {
  font-family: PingFang SC;
  font-weight: 700;
  color: #000000;
  font-size: 14px;
}
:deep(.el-input) {
  height: 40px;
  background-color: #ffffff;
}
:deep(.el-textarea) {
  height: 100px;
  background-color: #ffffff;
  .el-textarea__inner {
    height: 100px;
  }
}
.ClickButton {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: flex-end;
    .el-button {
      height: 40px;
      background-color: #ffffff;
      border: 1px solid;
      border-color: #cccccc;
    }
  }
}
.el-select,
.el-select-v2 {
  width: 100%;
}
</style>
